<template>
	<view class="login-container">
		<!-- 品牌展示区域 -->
		<view class="brand-section">
			<image class="logo" src="/static/images/login1.jpg" mode="aspectFit" />
			<text class="brand-name">农田小管家</text>
			<text class="brand-slogan">让每一寸土地都发挥最大价值</text>
		</view>

		<!-- 登录表单区域 -->
		<view class="form-container">
			<view class="tab-switch">
				<text class="tab-item" :class="{ active: activeTab === 'phone' }" @click="activeTab = 'phone'">
					手机号登录
				</text>
				<text class="tab-item" :class="{ active: activeTab === 'password' }" @click="activeTab = 'password'">
					密码登录
				</text>
			</view>

			<view class="form-content">
				<!-- 手机号登录表单 -->
				<view v-if="activeTab === 'phone'" class="phone-form">
					<view class="input-group">
						<view class="input-wrapper">
							<text class="prefix">+86</text>
							<uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
							<input v-model="phoneNumber" type="number" placeholder="请输入手机号" maxlength="11"
								class="input" />
						</view>
						<view v-if="phoneError" class="error-msg">{{ phoneError }}</view>
					</view>

					<view class="input-group">
						<view class="input-wrapper">
							<input v-model="verifyCode" type="number" placeholder="请输入验证码" maxlength="6"
								class="input" />
							<text class="verify-btn" :class="{ disabled: countdown > 0 }" @click="sendVerifyCode">
								{{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
							</text>
						</view>
						<view v-if="codeError" class="error-msg">{{ codeError }}</view>
					</view>
				</view>

				<!-- 密码登录表单 -->
				<view v-if="activeTab === 'password'" class="password-form">
					<view class="input-group">
						<view class="input-wrapper">
							<uni-icons type="person" size="18" color="#999"></uni-icons>
							<input v-model="username" type="text" placeholder="请输入用户名/手机号" class="input" />
						</view>
						<view v-if="nameError" class="error-msg">{{ nameError }}</view>
					</view>

					<view class="input-group">
						<view class="input-wrapper">
							<uni-icons type="locked" size="18" color="#999"></uni-icons>
							<input v-model="password" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码"
								class="input" />
							<uni-icons :type="showPassword ? 'eye' : 'eye-slash'" size="18" color="#999"
								@click="showPassword = !showPassword" />
						</view>
						<view v-if="pwdError" class="error-msg">{{ pwdError }}</view>
					</view>
				</view>

				<button class="login-btn" :class="{ disabled: !canLogin }" :disabled="!canLogin" @click="handleLogin">
					登录
				</button>
			</view>
		</view>

		<!-- 辅助功能区 -->
		<view class="assist-area">
			<text class="link-text" @click="navigateTo('forget')">忘记密码</text>
			<text class="divider">|</text>
			<text class="login-link" @click="goToreg">注册</text>
		</view>

		<!-- 第三方登录区域 -->
		<view class="third-party-login">
			<view class="divider-line">
				<text class="divider-text">其他登录方式</text>
			</view>
			<view class="third-icons">
				<view class="icon-wrapper">
					<uni-icons type="weixin" size="24" color="#07C160"></uni-icons>
				</view>
				<view class="icon-wrapper">
					<uni-icons type="qq" size="24" color="#12B7F5"></uni-icons>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';

	const activeTab = ref('phone');
	const phoneNumber = ref('');
	const verifyCode = ref('');
	const username = ref('');
	const password = ref('');
	const showPassword = ref(false);
	const countdown = ref(0);
	const phoneError = ref('');
	const codeError = ref('');
	const nameError = ref('');
	const pwdError = ref('');

	// 跳转到注册页
	const goToreg = () => {
		uni.navigateTo({
			url: '/pages/reg/reg'
		});
	};

	const canLogin = computed(() => {
		if (activeTab.value === 'phone') {
			return phoneNumber.value.length === 11 && verifyCode.value.length === 6;
		} else {
			return username.value.length > 0 && password.value.length >= 6;
		}
	});

	const sendVerifyCode = () => {
		if (countdown.value > 0) return;

		if (phoneNumber.value.length !== 11) {
			phoneError.value = '请输入正确的手机号';
			return;
		}

		phoneError.value = '';
		countdown.value = 60;

		const timer = setInterval(() => {
			countdown.value--;
			if (countdown.value <= 0) {
				clearInterval(timer);
			}
		}, 1000);

		// 这里应该是发送验证码的API调用
		console.log('发送验证码到:', phoneNumber.value);
	};

	//登录
	const handleLogin = () => {
		if (!canLogin.value) return;

		if (activeTab.value === 'phone') {
			console.log('手机号登录:', phoneNumber.value, verifyCode.value);
			// 调用手机号登录API
			uni.request({
				url: 'http://localhost:3000/users?phone=' + phoneNumber.value,
				method: "GET",
				success: (res) => {
					if (res.data.length > 0) {
						// 模拟验证码验证（实际项目应该调用后端API验证）
						if (verifyCode.value === '123456') { // 假设固定验证码为123456
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							});


							// 存储用户信息
							window.sessionStorage.setItem('userinfo', JSON.stringify({
								userId: res.data[0].id,
								phone: res.data[0].phone,
								username: res.data[0].username,
								password: res.data[0].password,
							}));

							// 跳转到个人中心
							uni.reLaunch({
								url: '/pages/my/my'
							});
						} else {
							uni.showToast({
								title: '验证码错误',
								icon: 'none'
							});
						}
					} else {
						// 手机号未注册
						uni.showModal({
							title: '提示',
							content: '该手机号未注册，是否立即注册？',
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/reg/reg?phone=' + phoneNumber
											.value
									});
								}
							}
						});
					}
				},
				fail: (err) => {
					console.error('登录请求失败:', err);
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					});
				}
			});
		} else {
			// 密码登录逻辑
			uni.request({
				url: 'http://localhost:3000/users?username=' + username.value,
				method: "GET",
				success: (res) => {
					console.log(res.data);
					if (res.data.length > 0) {
						// 说明存在该用户，可以进一步验证密码
						if (res.data[0].password == password.value) {
							// 密码匹配，登录成功
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							});

							let obj = {
								userId: res.data[0].id,
								username: res.data[0].username,
								phone: res.data[0].phone,
								password: res.data[0].password,
							};
							window.sessionStorage.setItem('userinfo', JSON.stringify(obj));
							uni.reLaunch({
								url: '/pages/my/my'
							});


						} else {
							// 密码错误
							uni.showToast({
								title: '密码错误，请检查',
								icon: 'none'
							});
							password.value = '';
						}
					} else {
						// 用户不存在
						uni.showToast({
							title: '用户不存在，请检查',
							icon: 'none'
						});
						username.value = '';
						password.value = '';
					}
				},
				fail: (err) => {
					console.error('登录请求失败:', err);
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					});
				}
			});
		}
	}
</script>

<style>
	page {
		height: 100%;
		background-color: #f8f8f8;
	}

	.login-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 100%;
		padding: 0 40rpx;
	}

	/* 品牌展示区域 */
	.brand-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 80rpx;
		margin-bottom: 60rpx;
	}

	.logo {
		width: 120px;
		height: 120px;
		margin-bottom: 20rpx;
	}

	.brand-name {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 12rpx;
	}

	.brand-slogan {
		font-size: 24rpx;
		color: #999;
	}

	/* 表单容器 */
	.form-container {
		width: 100%;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		margin-bottom: 40rpx;
	}

	/* 标签切换 */
	.tab-switch {
		display: flex;
		margin-bottom: 40rpx;
		border-bottom: 2rpx solid #eee;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding-bottom: 20rpx;
		font-size: 28rpx;
		color: #666;
		position: relative;
	}

	.tab-item.active {
		color: #07C160;
		font-weight: bold;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: -2rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 80rpx;
		height: 4rpx;
		background-color: #07C160;
		border-radius: 4rpx;
	}

	/* 输入框样式 */
	.input-group {
		margin-bottom: 40rpx;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		height: 88rpx;
		border-bottom: 2rpx solid #eee;
		padding: 0 10rpx;
	}

	.input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
		padding: 0 20rpx;
		color: #333;
	}

	.prefix {
		font-size: 28rpx;
		color: #333;
		margin-right: 10rpx;
	}

	.verify-btn {
		font-size: 24rpx;
		color: #07C160;
		padding: 10rpx 20rpx;
		border-radius: 40rpx;
		background-color: rgba(7, 193, 96, 0.1);
	}

	.verify-btn.disabled {
		color: #999;
		background-color: rgba(153, 153, 153, 0.1);
	}

	.error-msg {
		font-size: 24rpx;
		color: #ff4d4f;
		margin-top: 10rpx;
		height: 30rpx;
		line-height: 30rpx;
	}

	/* 登录按钮 */
	.login-btn {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		background-color: #07C160;
		color: #fff;
		font-size: 32rpx;
		border-radius: 44rpx;
		margin-top: 20rpx;
	}

	.login-btn.disabled {
		opacity: 0.6;
	}

	/* 辅助功能区 */
	.assist-area {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 60rpx;
	}

	.link-text {
		font-size: 24rpx;
		color: #666;
		padding: 0 20rpx;
	}

	.divider {
		font-size: 24rpx;
		color: #ddd;
	}

	/* 第三方登录 */
	.third-party-login {
		width: 100%;
		margin-top: auto;
		margin-bottom: 60rpx;
	}

	.divider-line {
		position: relative;
		height: 2rpx;
		background-color: #eee;
		margin: 40rpx 0;
	}

	.divider-text {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		font-size: 24rpx;
		color: #999;
		background-color: #f8f8f8;
		padding: 0 20rpx;
	}

	.third-icons {
		display: flex;
		justify-content: center;
		gap: 80rpx;
	}

	.icon-wrapper {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	}
</style>